import snowflake.client

from apps.background.models import Doctor, TimeSlot


# 启动snowflake服务（实际使用时应该在系统服务中启动）
# 建议在项目启动前运行：snowflake_start_server --worker=1

def generate_snowflake_id():
    """
    使用pysnowflake生成唯一ID
    """
    try:
        return snowflake.client.get_guid()
    except Exception as e:
        # 如果snowflake服务未启动，返回错误信息
        print(f"Snowflake服务错误: {str(e)}，请确保已运行snowflake_start_server")
        # 返回一个基于时间戳的备用ID
        import time
        import random
        return int(time.time() * 1000) * 1000 + random.randint(0, 999)

def get_order_table_index(order_id):
    """
    根据订单ID确定订单表索引（0, 1, 2）
    """
    # 使用ID的最后一位数字进行取模，确保更均匀分布
    return int(str(order_id)[-1]) % 3

def get_order_table_name(order_id):
    """
    根据订单ID获取完整表名
    """
    return f"reservation_order_{get_order_table_index(order_id)}"

def get_doctor_info(doctor_id):
    """
    根据医生ID获取医生信息
    """

    try:
        doctor = Doctor.objects.get(id=doctor_id)
        return {
            'id': doctor.id,
            'name': doctor.name,
            'title': doctor.title,
            'department': doctor.department.name if hasattr(doctor, 'department') and doctor.department else "",
            'hospital_name': doctor.hospital.name if hasattr(doctor, 'hospital') and doctor.hospital else "",
            'hospital_address': doctor.hospital.address if hasattr(doctor, 'hospital') and doctor.hospital else ""
        }
    except Doctor.DoesNotExist:
        return None
    except Exception as e:
        print(f"获取医生信息错误: {str(e)}")
        return None

def get_time_slot_info(time_slot_id):
    """
    根据时间段ID获取预约时间信息
    """

    try:
        # 获取时间段
        slot = TimeSlot.objects.get(id=time_slot_id)
        
        # 获取关联的排班和医生信息
        schedule = slot.schedule
        doctor = schedule.doctor
        
        # 格式化时间
        time_slot_str = f"{slot.start_time.strftime('%H:%M')}-{slot.end_time.strftime('%H:%M')}"
        
        # 计算星期几
        weekday = get_weekday_display(schedule.date.weekday())
        
        return {
            'id': slot.id,
            'date': schedule.date,
            'weekday': weekday,
            'time_slot': time_slot_str,
            'fee': f"¥{doctor.price}"
        }
    except TimeSlot.DoesNotExist:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"时间段不存在: {time_slot_id}")
        return None
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"获取时间段信息错误: {str(e)}")
        return None

def get_weekday_display(weekday):
    """
    将数字星期转换为中文显示
    """
    weekdays = {
        0: "周一",
        1: "周二", 
        2: "周三",
        3: "周四",
        4: "周五",
        5: "周六",
        6: "周日"
    }
    return weekdays.get(weekday, "未知") 